package com.bandit.controller.back;

import com.alibaba.fastjson.JSONObject;
import com.bandit.pojo.Message;
import com.bandit.pojo.MsgType;
import com.bandit.service.MessageService;
import com.bandit.service.MsgTypeService;
import com.bandit.utils.LayResult;
import com.bandit.utils.PageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/back/message")
public class MessageBackController {

    private static final String prefix = "back/message";

    @Autowired
    MessageService messageService;

    @Autowired
    MsgTypeService msgTypeService;

    @RequiresPermissions("back:message:list")
    @GetMapping("/list")
    public String toList(Model model){
        List<MsgType> typeList = msgTypeService.selectMsgTypeList(new MsgType());
        model.addAttribute("typeList",typeList);
        return prefix + "/list";
    }

    @RequiresPermissions("back:message:edit")
    @GetMapping("/edit")
    public String toEdit(@RequestParam("msgID") int msgID, Model model){
        Message message = messageService.selectMessageByMsgID(msgID);
        List<MsgType> typeList = msgTypeService.selectMsgTypeList(new MsgType());
        model.addAttribute("message",message);
        model.addAttribute("typeList",typeList);
        return prefix + "/edit";
    }

    @RequiresPermissions("back:message:add")
    @GetMapping("/add")
    public String toAdd(Model model){
        List<MsgType> typeList = msgTypeService.selectMsgTypeList(new MsgType());
        model.addAttribute("typeList",typeList);
        return prefix + "/add";
    }

    @RequiresPermissions("back:message:delete")
    @GetMapping("/delete")
    @ResponseBody
    public LayResult delete(@RequestParam("msgID") int msgID){
        int update = messageService.deleteMessageByMsgID(msgID);
        if (update == 0){
            return new LayResult(500);
        }else return new LayResult();

    }

    @RequiresPermissions("back:message:delete")
    @PostMapping("/deleteByIDS")
    @ResponseBody
    public LayResult deleteByIDS(String[] msgIDS){
        for (String msgID : msgIDS) {
            System.out.println(msgID);
        }
        int update = messageService.deleteMessageByMsgIDs(msgIDS);
        if (update == 0){
            return new LayResult(500);
        }else return new LayResult();
    }

    @GetMapping("/query")
    @ResponseBody
    public LayResult selectList(@RequestParam("page")int page,@RequestParam("limit")int limit){
        List<Message> messageList = messageService.selectMessageList(new Message());
        //分页开始
        PageUtils pageUtils = new PageUtils(messageList, page, limit);
        List records = pageUtils.getRecords();
        //分页结束
        LayResult layResult = new LayResult(messageList.size());
        return layResult.put(LayResult.DATA_TAG,records);
    }

    @PostMapping("/editConfirm")
    @ResponseBody
    public LayResult editConfirm(Message message){
        System.out.println("edit");
        message.setReleaseDate(new Date());
        int updateMessage = messageService.updateMessage(message);
        if(updateMessage == 0){
            System.out.println("更新失败");
            return new LayResult(500);
        }else return new LayResult();
    }

    @PostMapping("/addConfirm")
    @ResponseBody
    public LayResult addConfirm(Message message){
        message.setReleaseDate(new Date());
        int updateMessage = messageService.insertMessage(message);
        if(updateMessage == 0){
            System.out.println("插入失败");
            return new LayResult(500);
        }else return new LayResult();
    }

    /**
     * 图片上传处理
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadImage")
    @ResponseBody
    public JSONObject uploadImg (@RequestParam(value = "editormd-image-file", required = true) MultipartFile file) throws Exception{

        //文件后缀
        String trueFileName = file.getOriginalFilename();
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        //文件名随机+后缀
        String fileName = "message-"+ UUID.randomUUID().toString().replaceAll("-", "") +suffix;

        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
        //项目路径绝对mywebproject\target\classes
        String absolutePath = projectPath.getAbsolutePath();
        //放入/static/upload/目录下
        String path = absolutePath+"/static/upload/";
        System.out.println(path);

        //没有就创建文件夹
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回给前端文件位置
        JSONObject res = new JSONObject();
        res.put("url", "/upload/"+fileName);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;

    }


}
